package com.iasku.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.serialization.SoapObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.iasku.constant.Constant;
import com.iasku.entity.IaskuExam;
import com.iasku.entity.IaskuQuestion;
import com.iasku.entity.UserErrorBook;
import com.iasku.entity.UserHomework;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.iaskueleclass_phone.ReturnData;
import com.iasku.util.BaseUtil;
import com.iasku.util.DateUtil;
import com.iasku.util.IaskuUtil;
import com.iasku.util.SoapUtil;

public class JSONParser {
    private static final String IS_CORRECT_YES = "是";
    private static final String IS_CORRECT_NO = "否";

    public static ReturnData<List<UserHomework>> getHomeworkData(int status, String json_result, SharedPreferences pref) {
        ReturnData<List<UserHomework>> data = new ReturnData<List<UserHomework>>();
        List<UserHomework> list = new ArrayList<UserHomework>();
        try {
            JSONObject resultJSON = new JSONObject(json_result);
            data.status = resultJSON.getInt("error_no");
            if (data.status == 0) {
                JSONArray mJSONArray = new JSONArray(resultJSON.getString("result"));
                if (mJSONArray.length() > 0) {
                    for (int i = 0; i < mJSONArray.length(); i++) {
                        UserHomework work = new UserHomework();
                        work.setStatus(status);
                        JSONObject mJSONObject = mJSONArray.getJSONObject(i);
                        work.setExamid(mJSONObject.getString("eid"));
                        work.setExamname(mJSONObject.getString("examname"));
                        work.setStart_dateline(DateUtil.getDateTime(mJSONObject.getLong("dateline")));
                        String end_dateline = mJSONObject.getString("submit_dateline");
                        if ("null".equals(end_dateline) || "".equals(end_dateline)) {
                            work.setEnd_dateline("");
                        } else {
                            work.setEnd_dateline(DateUtil.getDateTime(mJSONObject.getLong("submit_dateline")));
                        }
                        String username = mJSONObject.getString("pubname");
                        String truename = pref.getString(username, "");
                        if("".equals(truename)){
                            truename = getTruename(username);
                            work.setTeacher_truename(truename);
                            Editor editor = pref.edit();
                            editor.putString(username, truename);
                            editor.commit();
                        }
                        work.setTeacher_truename(truename);
                        work.setSumScore(mJSONObject.getString("sum_score"));
                        list.add(work);
                    }
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        data.setData(list);
        return data;
    }

    private static String getTruename(String iaskuusername) {
        String methodname = "GetSchoolUser_info";
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("sid", Constant.USER_SHCOOL_ID);
        params.put("iaskuuname", iaskuusername);
        try {
            SoapObject res = SoapUtil.getResponseSoapObject(params, methodname, Constant.NAMESPACE2, Constant.URL2);
            if (res != null) {
                String result = res.getProperty(methodname + Constant.RESULT).toString();
                if (result.contains("::")) {
                    return iaskuusername;
                } else {
                    return result.split(":")[1];
                }
            } else {
                return iaskuusername;
            }
        } catch (Exception e) {
            return iaskuusername;
        }

    }

    public static ReturnData<ArrayList<UserErrorBook>> getErrorQuestionData(String json_result) {
        ReturnData<ArrayList<UserErrorBook>> data = new ReturnData<ArrayList<UserErrorBook>>();
        ArrayList<UserErrorBook> list = new ArrayList<UserErrorBook>();
        try {
            JSONObject resultJSON = new JSONObject(json_result);
            data.status = resultJSON.getInt("error_no");
            if (data.status == 0) {
                JSONArray mJSONArray = new JSONArray(resultJSON.getString("result"));
                int length = mJSONArray.length();
                if (length > 0) {
                    for (int i = 0; i < length; i++) {
                        JSONObject mJSONObject = mJSONArray.getJSONObject(i);
                        String subjectname = mJSONObject.getString("subjectname");
                        String questiontype = mJSONObject.getString("questiontype");
                        if (("null".equals(subjectname) || "".equals(questiontype))
                                || ("null".equals(questiontype) || "".equals(questiontype))) {
                            continue;
                        }
                        UserErrorBook eQue = new UserErrorBook();
                        eQue.setQuestionno(mJSONObject.getString("questionno"));
                        eQue.setSubjectname(subjectname);
                        eQue.setQuestionType(questiontype);
                        eQue.setSubmitTime(DateUtil.getDateTime(mJSONObject.getLong("subtime")));
                        eQue.setExamid(mJSONObject.getString("exemid"));
                        eQue.setExamname(subjectname);
                        int maxgrade = mJSONObject.getInt("maxgrade");
                        eQue.setMaxScore(String.valueOf(maxgrade));
                        int times = mJSONObject.getInt("times");
                        String grade = mJSONObject.getString("grade");
                        if (times == 1) {
                            eQue.setGetScore(grade);
                            eQue.setIsCorrectedStr(IS_CORRECT_NO);
                        } else {
                            if (times >= Constant.ERROR_TIMES) {
                                eQue.setIsCorrectedStr(IS_CORRECT_YES);
                                String newgrade = mJSONObject.has("newgrade") ? mJSONObject.getString("newgrade")
                                        : grade;
                                newgrade = "null".equals(newgrade) ? grade : mJSONObject.getString("newgrade");
                                eQue.setGetScore(newgrade);
                            } else {
                                if (mJSONObject.has("newgrade")) {
                                    String newgrade = mJSONObject.getString("newgrade");
                                    eQue.setGetScore(newgrade);
                                    if (!"null".equals(newgrade)) {
                                        if (Integer.parseInt(newgrade) == maxgrade) {
                                            eQue.setIsCorrectedStr(IS_CORRECT_YES);
                                        } else {
                                            eQue.setIsCorrectedStr(IS_CORRECT_NO);
                                        }
                                    } else {
                                        eQue.setGetScore(grade);
                                        eQue.setIsCorrectedStr(IS_CORRECT_NO);
                                    }
                                }
                            }
                        }
                        list.add(eQue);
                    }
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        data.setData(list);
        return data;
    }

    public static ReturnData<IaskuExam> getExam(Context mContext,String json_result) {
        ReturnData<IaskuExam> data = new ReturnData<IaskuExam>();
        IaskuExam iaskuExam = new IaskuExam();
        try {
            JSONObject resultJSON = new JSONObject(json_result);
            data.status = resultJSON.getInt("error_no");
            if (data.status == 0) {
                String result = resultJSON.getString("result");
                JSONObject mJSONObject = new JSONObject(result);
                iaskuExam.setExamid(mJSONObject.getString("paper_id"));
                iaskuExam.setExamname(mJSONObject.getString("paper_name"));
                iaskuExam.setSubjectid(mJSONObject.getInt("subject_id"));
                JSONArray mJSONArray = new JSONArray(mJSONObject.optString("question_list"));
                if (mJSONArray.length() > 0) {
                    List<IaskuQuestion> list = new ArrayList<IaskuQuestion>();
                    for (int i = 0; i < mJSONArray.length(); i++) {
                        JSONObject quesJSON = mJSONArray.getJSONObject(i);
                        IaskuQuestion iQues = new IaskuQuestion();
                        int que_type_id = quesJSON.getInt("question_type");
                        iQues.setQuestionno(quesJSON.getString("question_id"));
                        iQues.setQuestion_type_id(que_type_id);
                        iQues.setQuestion_score(quesJSON.getString("question_score"));
                        iQues.setQuestiontype_name(IaskuUtil.getQuestionTypeName(mContext,quesJSON.getInt("question_type")));
                        switch (que_type_id) {
                        case Constant.TYPE_DANX:
                        case Constant.TYPE_DUOX:
                        case Constant.TYPE_XUANZ:
                            iQues.setIsattach(Constant.ATTACH_NO);
                            break;

                        default:
                            iQues.setIsattach(Constant.ATTACH_YES);
                            break;
                        }
                        list.add(iQues);
                    }
                    iaskuExam.setQuestions(list);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        data.setData(iaskuExam);
        return data;
    }

    public static void getUserAnswer(IaskuQuestion iQuestion, String json_result) {
        ReturnData<IaskuQuestion> data = new ReturnData<IaskuQuestion>();
        try{
            JSONObject resultJSON = new JSONObject(json_result);
            data.status = resultJSON.getInt("error_no");
            if(data.status == 0){
                JSONObject mJSONObject = new JSONObject(resultJSON.getString("result"));
                if(iQuestion != null){
                    iQuestion.setTotal(mJSONObject.optInt("total"));
                    iQuestion.setUseranswer(mJSONObject.optString("answer"));
                    String getscore = mJSONObject.optString("grade");
                    if("null".equals(getscore)){
                        getscore = "0";
                    }
                    iQuestion.setUserscore(getscore);
                    iQuestion.setAttachStr(mJSONObject.optString("attach"));
                    iQuestion.setAnswerid(mJSONObject.optString("answerid"));
                    iQuestion.setNewanswer(mJSONObject.optString("newanswer"));
                    iQuestion.setNewscore(mJSONObject.optString("newgrade"));
                    iQuestion.setSubmitTimes(mJSONObject.optInt("times"));
                    data.setData(iQuestion);
                }
            }
        }catch(Exception e){
        }
    }

    public static ReturnData<String> submitUserAnswer(String result) {
        ReturnData<String> mData = new ReturnData<String>();
        try {
            JSONObject resultJSON = new JSONObject(result);
            mData.status = resultJSON.getInt("error_no");
            if(mData.status == 0){
                JSONObject mJSONObject = new JSONObject(resultJSON.getString("result"));
                mData.setData(mJSONObject.optString("answerid"));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mData;
    }

    public static String submitExam(String result) {
        String msg = "";
        try {
            JSONObject resultJSON; resultJSON = new JSONObject(result);
            int status = resultJSON.getInt("error_no");
            if(status == 0){
                msg = "提交成功";
            }else{
               msg = "提交失败，请稍后重新提交";
            }
        } catch (JSONException e) {
            msg = "提交失败，请稍后重新提交";
        }
        return msg;
    }

    public static HashMap<String, String> getExamTeacher(String result) {
        HashMap<String, String> map = new HashMap<String, String>();
        try {
            JSONObject tJSON = new JSONObject(result);
            int error_no = tJSON.getInt("error_no");
            switch (error_no) {
            case 0:
                JSONObject mJSONObject = new JSONObject(tJSON.getString("result"));
                map.put("teachername", mJSONObject.getString("username"));
                map.put("subject_id", mJSONObject.getString("sid"));
                map.put("grade_id", mJSONObject.getString("gid"));
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static HashMap<String, String> autorecommendquestion(String result) {
        HashMap<String, String> map = new HashMap<String, String>();
        try {
            JSONObject qJSON = new JSONObject(result);
            int error_no = qJSON.getInt("error_no");
            switch (error_no) {
            case 0:
                JSONObject mJSONObject = new JSONObject(qJSON.getString("result"));
                map.put("question_no_new", mJSONObject.optString("question_id"));
                map.put("knowpoint_text_new", mJSONObject.optString("knowledge_text"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static ArrayList<String> getClassesByUsername(String result) {
        ArrayList<String> classIds = new ArrayList<String>();
        try {
            JSONObject mJSONObject = new JSONObject(result);
            int error_no = mJSONObject.getInt("error_no");
            switch (error_no) {
            case 0:
                JSONArray mJSONArray = mJSONObject.getJSONArray("result");
                if (mJSONArray.length() > 0) {
                    for (int i = 0; i < mJSONArray.length(); i++) {
                        JSONObject mJSONObject2 = mJSONArray.getJSONObject(i);
                        classIds.add(mJSONObject2.getString("classid"));
                    }
                }
                break;
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return classIds;
    }
}
